package com.jinyu.jyly.ui.mine.order.detail;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.king.image.imageviewer.ImageViewer;
import com.king.image.imageviewer.loader.GlideImageLoader;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.jinyu.jyly.R;
import com.jinyu.jyly.base.BaseActivity;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.ShowOrderPayInfo;
import com.jinyu.jyly.global.GlobalConstants;
import com.jinyu.jyly.net.http.HttpUrl;
import com.jinyu.jyly.utils.AES;
import com.jinyu.jyly.utils.SharedPreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 展示支付方式
 */
public class ShowOrderPayActivity extends BaseActivity<OrderDetailPresenter> implements OrderDetailContract.View {

    @BindView(R.id.fake_status_bar)
    View fakeStatusBar;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_title_view)
    RelativeLayout rlTitleView;
    @BindView(R.id.tv_order_state)
    TextView tvOrderState;
    @BindView(R.id.tv_weichat_number)
    TextView tvWeichatNumber;
    @BindView(R.id.iv_weichat_img)
    ImageView ivWeichatImg;
    @BindView(R.id.tv_ali_number)
    TextView tvAliNumber;
    @BindView(R.id.iv_ali_img)
    ImageView ivAliImg;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.tv_bank_number)
    TextView tvBankNumber;
    @BindView(R.id.tv_bank_user)
    TextView tvBankUser;
    @BindView(R.id.tv_zhihang_name)
    TextView tvZhihangName;
    @BindView(R.id.iv_pay_img)
    ImageView iv_pay_img;


    private OrderDetailPresenter presenter;
    private int id;
    private String weipic;
    private String ali_pic;
    private int themeId;
    private final int REQUEST_HEADER = 1111;
    private UploadManager uploadManager;
    private String qiniuToken;
    private String qiNiuImg = "";


    @Override
    public int getLayout() {
        return R.layout.activity_order_show_order_pay;
    }

    @Override
    protected OrderDetailPresenter getPresenter() {
        if (presenter == null) {
            presenter = new OrderDetailPresenter(this, this);
        }
        return presenter;
    }


    @Override
    protected void initEventAndData() {
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        qiniuToken = (String) SharedPreferencesUtils.getParam(this, GlobalConstants.QINIU_TOKEN, "");
        themeId = R.style.picture_default_style;
        initQiNiu();
        initData();
        setPermissions();
    }

    /**
     * 初始化七牛云
     */
    private void initQiNiu() {
        Configuration config = new Configuration.Builder()
                .connectTimeout(90)              // 链接超时。默认90秒
                .useHttps(true)                  // 是否使用https上传域名
                .useConcurrentResumeUpload(true) // 使用并发上传，使用并发上传时，除最后一块大小不定外，其余每个块大小固定为4M，
                .concurrentTaskCount(3)          // 并发上传线程数量为3
                .responseTimeout(90)             // 服务器响应超时。默认90秒
                .recorder(null)              // recorder分片上传时，已上传片记录器。默认null
//                .recorder(recorder, keyGen)      // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
//                .zone(FixedZone.zone0)           // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
                .build();
// 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }

    private void initData() {
        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        int status = intent.getIntExtra("status", 0);
        tvOrderState.setText("订单待付款");
        try {
            //获取mine
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", id);
            String param = AES.encryptToHexString(jsonObject.toString());
            presenter.getorderPayment(param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onFailer(Throwable throwable) {

    }


    /**
     * 设置相关权限
     */
    private void setPermissions() {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(ShowOrderPayActivity.this);
                } else {
                    Toast.makeText(ShowOrderPayActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }


    @Override
    public void onGetOrderPayment(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                try {
                    String decrypt = AES.decrypt(infoBean.getData());
                    Gson gson = new Gson();
                    ShowOrderPayInfo showOrderPayInfo = gson.fromJson(decrypt, ShowOrderPayInfo.class);
                    if (showOrderPayInfo != null) {
                        tvAliNumber.setText(showOrderPayInfo.getAli_num());
                        tvBankName.setText(showOrderPayInfo.getBank());
                        tvBankNumber.setText(showOrderPayInfo.getBank_num());
                        tvBankUser.setText(showOrderPayInfo.getBank_name());
                        tvZhihangName.setText(showOrderPayInfo.getBank_little_name());
                        tvWeichatNumber.setText(showOrderPayInfo.getWei_num());
                        weipic = showOrderPayInfo.getWei_pic();
                        ali_pic = showOrderPayInfo.getAli_pic();

                        RequestOptions options = new RequestOptions();
                        options.error(R.mipmap.space_list);
                        Glide.with(mContext).load(showOrderPayInfo.getWei_pic())
                                .apply(options)
                                .into(ivWeichatImg);

                        RequestOptions optionss = new RequestOptions();
                        options.error(R.mipmap.space_list);
                        Glide.with(mContext).load(showOrderPayInfo.getAli_pic())
                                .apply(optionss)
                                .into(ivAliImg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
    }

    /**
     * 更新订单状态
     *
     * @param infoBean
     */
    @Override
    public void onChangeOrder(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                String data = infoBean.getData();
                finish();
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }


    @OnClick({R.id.iv_weichat_img, R.id.iv_ali_img, R.id.btn_pay, R.id.iv_pay_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_weichat_img:
                ImageViewer.load(weipic)//要加载的图片数据，单张或多张
                        .imageLoader(new GlideImageLoader())//加载器，imageLoader必须配置，目前内置的有GlideImageLoader或PicassoImageLoader，也可以自己实现
                        .start(this, ivWeichatImg);//activity or fragment, 跳转时的共享元素视图
                break;
            case R.id.iv_ali_img:
                ImageViewer.load(ali_pic)//要加载的图片数据，单张或多张
                        .imageLoader(new GlideImageLoader())//加载器，imageLoader必须配置，目前内置的有GlideImageLoader或PicassoImageLoader，也可以自己实现
                        .start(this, ivAliImg);//activity or fragment, 跳转时的共享元素视图
                break;
            case R.id.btn_pay:
                //去支付
                setSignOutApp();
//                transferGiftDialog();
                break;
            case R.id.iv_pay_img:
                //付款截图
                //上传图片
                setPicutureImage(1, PictureConfig.SINGLE, null, REQUEST_HEADER);
                break;
        }
    }

    private int imgId = -1;

    @Override
    public void onUpdataImg(AllInfoBean infoBean) {
        switch (infoBean.getStatus()) {
            case 200:
                String beanData = infoBean.getData();
                String result = null;
                try {
                    result = AES.decrypt(beanData);
                    JSONObject rootObject = new JSONObject(result);
                    imgId = rootObject.optInt("id");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 打开选择器
     */
    private void setPicutureImage(int maxNum, int mode, List<LocalMedia> selectList, int requestcode) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(mode)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .previewVideo(true)// 是否可预览视频
                .enablePreviewAudio(true) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(false)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(requestcode);//结果回调onActivityResult code
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_HEADER:
                    //
                    String img_Url = getRequestCodeData(data);
                    File tempFile = new File(img_Url);
                    String fileName = tempFile.getName();
                    //上传图片到自己服务器（暂时不用）
//                    List<MultipartBody.Part> parts = new ArrayList<>();
//                    parts.add(toRequestBodyOfImage(tempFile, fileName));
//                    presenter.updataImg(parts);
                    mTipDialog.show();
                    //直接上传到七牛云
                    //设置上传后文件的key
                    uploadManager.put(img_Url, fileName, qiniuToken, new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo rinfo, JSONObject response) {
                            mTipDialog.dismiss();
                            //显示上传后文件的url
                            if (rinfo.isOK()) {
                                qiNiuImg = key;
                                mTipDialog.show();
                                RequestOptions options = new RequestOptions()
                                        .centerCrop()
                                        .placeholder(R.drawable.image_loding) //占位符 也就是加载中的图片
                                        .error(R.mipmap.image_error)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL);
                                Glide.with(ShowOrderPayActivity.this)
                                        .load(HttpUrl.QIUNIU_PATH +key)
                                        .apply(options)
                                        .addListener(new RequestListener<Drawable>() {
                                            @Override
                                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                                mTipDialog.dismiss();
                                                showToast("网络异常，上传失败，请稍后重试");
                                                Log.e("shibai",e.toString());
                                                return false;
                                            }

                                            @Override
                                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                                mTipDialog.dismiss();
                                                showToast("上传成功");
                                                return false;
                                            }
                                        })
                                        .into(iv_pay_img);
                                Log.i("qiniu", "Upload Success");
                            } else {
                                qiNiuImg = "0";
                                Log.i("qiniu", "Upload Fail");
                                //如果失败，这里可以把 info 信息上报自己的服务器，便于后面分析上传错误原因
                            }
                        }
                    }, new UploadOptions(null, "image/png", true, null, null));

                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 获取相关data数据
     *
     * @param data
     */
    private String getRequestCodeData(Intent data) {
        String path = "";
        if (data == null) {
            showToast("图片选择失败");
            return "";
        }
        List<LocalMedia> licenseList = PictureSelector.obtainMultipleResult(data);
        if (licenseList != null && licenseList.size() != 0) {
            LocalMedia localMedia = licenseList.get(0);
            if (localMedia.isCut() && !localMedia.isCompressed()) {
                // 裁剪过
                path = localMedia.getCutPath();
            } else if (localMedia.isCompressed() || (localMedia.isCut() && localMedia.isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                path = localMedia.getCompressPath();
            } else {
                // 原图
                path = localMedia.getPath();
            }
            Log.e("选择了图片", path);
        }
        return path;
    }


    private MultipartBody.Part toRequestBodyOfImage(File tempFile, String name) {
        RequestBody fileRQ = RequestBody.create(MediaType.parse("image/jpg"), tempFile);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", name, fileRQ);
        return part;
    }


    /**
     *
     */
    private Dialog mtransferDialog;

    private void transferGiftDialog() {
        mtransferDialog = new Dialog(this, R.style.wheelviewDialog);
        mtransferDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View outerView = LayoutInflater.from(this).inflate(R.layout.dialog_pay_psw, null);
        ImageView iv_close_open = outerView.findViewById(R.id.iv_close_open);
        TextView tv_close = outerView.findViewById(R.id.tv_close);
        TextView tv_sure = outerView.findViewById(R.id.tv_sure);
        TextView payPsw = outerView.findViewById(R.id.et_pay_psw);
        mtransferDialog.setCanceledOnTouchOutside(false);
        mtransferDialog.setContentView(outerView);
        // 将对话框的大小按屏幕大小的百分比设置
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window window = mtransferDialog.getWindow();
        WindowManager.LayoutParams lp = mtransferDialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth() * 0.72); //设置宽度
//      lp.height = (int) (display.getHeight() * 0.68);//设置高度
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        mtransferDialog.show();
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String psw = payPsw.getText().toString().trim();
                if (TextUtils.isEmpty(psw)) {
                    showToast("支付密码不能为空");
                    return;
                }

//                if (imgId == -1) {
//                    showToast("请选择图片");
//                    return;
//                }

                if (TextUtils.isEmpty(qiNiuImg)) {
                    showToast("请选择截图");
                    return;
                }

                if ("0".equals(qiNiuImg)) {
                    showToast("上传截图失败，请重新上传");
                    return;
                }

                mtransferDialog.dismiss();
                try {
                    //获取mine
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", id);
                    jsonObject.put("cat", 1);
                    jsonObject.put("pwd", psw);
                    jsonObject.put("pic", 0);
                    jsonObject.put("qiniu", qiNiuImg);
                    String param = AES.encryptToHexString(jsonObject.toString());
                    presenter.getChangeOrder(param);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        iv_close_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mtransferDialog.dismiss();
            }
        });

        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mtransferDialog.dismiss();
            }
        });
    }


    //确认是否已付款
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    private void setSignOutApp() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("您确认已经付过款了吗，确认后您的保证金将失效")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        transferGiftDialog();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }
}
